<?php

class Html{
protected $html = '';
function html(){
	echo $this->html;	
}
}

abstract class Table_navigator extends Html{	
	
protected
	$table_id = 'table',
	$navigator_link = '#',
	$items_a_page = 5;

abstract protected function mysql_string();
abstract protected function a_row($num_row,$num_item,$data);
abstract protected function main();

private 
	$dbresult,
	$num_items,
	$num_pages,
	$cur_page,
	$start_item;

protected function Table(){
	$this->num_items = mysql_num_rows(mysql_query(($this->mysql_string())));
	$this->num_pages = ceil($this->num_items/$this->items_a_page);
	$this->cur_page = max(min($_SESSION['page'],$this->num_pages),1);
	
	$this->start_item = ($this->cur_page-1)*$this->items_a_page;
	$this->dbresult = mysql_query($this->mysql_string()." LIMIT $this->start_item,$this->items_a_page");	

	$this->html = $this->main();	
}

protected function table_rows(){
	$html = '';
	$count = 0;
	while ($row=mysql_fetch_array($this->dbresult)){		
		$html .= $this->a_row($count,$this->start_item+$count+1,$row);
		$count++;
	}
	return $html;
}

protected function navigator(){
	$html_navigator = <<<HTML
<div id="navigator">
	%s
</div>
HTML;

	$html_nav_item = <<<HTML
	<a href="%s">%s</a>	
HTML;

	$html_nav_item_selected = <<<HTML
	<a id="selected">%s</a>	
HTML;

	$html_nav_item_more = <<<HTML
	<a>...</a>
HTML;

	$inner_html = '';

	if ($this->num_pages <= 1){return '';}
	
	$min_page = $this->cur_page - 2;
	if ($min_page < 1) { 
		$min_page = 1;
		$max_page = min(5, $this->num_pages);	
	} else {
		$max_page = $this->cur_page + 2;
		if ($max_page > $this->num_pages) {
			$max_page = $this->num_pages;
			$min_page = max($this->num_pages - 4, 1);
		}
	}
	
	$inner_html .= sprintf($html_nav_item,sprintf($this->navigator_link,$min_page),'Đầu');
	if ($min_page > 1) {$inner_html .= sprintf($html_nav_item_more);}	
	
	for ($i=$min_page; $i<=$max_page; $i++){
		if ($i==$this->cur_page){
			$inner_html .= sprintf($html_nav_item_selected,$i);
		} else {
			$inner_html .= sprintf($html_nav_item,sprintf($this->navigator_link,$i),$i);	
		}
	}	
    
    if ($max_page < $this->num_pages) {$inner_html .= sprintf($html_nav_item_more);}    
    $inner_html .= sprintf($html_nav_item,sprintf($this->navigator_link,$max_page),'Cuối');
    
    return sprintf($html_navigator,$inner_html);
}
}

?>